package com.zhuiyun.plugs.thirdlogin.util;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.zhuiyun.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/***
 *  处理请求相关相关工具类
 * @author 飞龙
 * @date 2022年8月29日1
 */
public class UrlUtils {

    private static Logger logger= LoggerFactory.getLogger(UrlUtils.class);



    /***
     * 格式化相关授权地址
     *
     * @param request  请求对象
     * @param callBackUrl 回调地址
     * @param authUrl 授权地址
     * @param clientId 客户端授权id
     * @param scope  授权url回调后标记接口作用域
     * @return 填充后的第三方授权登录地址
     */
    public static String formatRequestAuthUrl(HttpServletRequest request,String callBackUrl,String authUrl,String clientId,String scope) {
        String url = "";
        String host = request.getHeader("host");
        String redirectUrl="http://"+host+callBackUrl;
        String state=request.getParameter("state");
        String state_str= StringUtils.isEmpty(state)?"":"&state="+state;
        url=authUrl.replaceAll("\\[client_id\\]",clientId).replaceAll("\\[redirect_uri\\]",redirectUrl).replaceAll("\\[scope\\]",scope)+state_str;
        return url;
    }


    /***
     *  发起post请求并获取响应结果
     * @param url 请求url
     * @param params 参数（key,value格式）
     * @return 响应结果
     */
    public static String requestUrl(String url, Method method, Map<String,Object> params) {
        try {
            if(ObjectUtil.isNull(method)){
                method = Method.GET;
            }
            Map<String,String> headerMap = new HashMap<>(2);
            headerMap.put("User-Agent" , "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:70.0) Gecko/20100101 Firefox/70.0");
            HttpRequest httpRequest = null;
            if( ObjectUtil.isNotNull(params) ){
               httpRequest = new HttpRequest(url).method(method)
                        .addHeaders(headerMap).form(params);
            }else{
                httpRequest = new HttpRequest(url).method(method)
                        .addHeaders(headerMap);
            }
            HttpResponse response = httpRequest.execute();
            String result = response.body();
            return result;
        } catch (Exception e) {
            logger.error("post请求{}异常",url,e);
            return "";
        }
    }




}
